//
//  NoFinishDetailController.m
//  PersonnelWashCar
//
//  Created by 张越 on 16/4/27.
//  Copyright © 2016年 张越. All rights reserved.
//

#import "NoFinishDetailController.h"
#import "DetailViewController.h"
#import "AffirmOrderController.h"

@interface NoFinishDetailController ()
/**
 *  百度地图
 */
@property (nonatomic, strong) BMKMapView *mapView;
/**
 *  检索对象
 */
@property (nonatomic, strong) BMKPoiSearch* poisearch;
@property (strong, nonatomic) IBOutlet UIScrollView *orderScrollView;
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) CLGeocoder *gecoder;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *line1;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *line2;
@property (strong, nonatomic) IBOutlet UILabel *mapLabel;
@property (strong, nonatomic) IBOutlet UIView *carBackgroundView;
@property (strong, nonatomic) IBOutlet UIView *backgroundView;
@property (strong, nonatomic) IBOutlet UILabel *orderName;
@property (strong, nonatomic) IBOutlet UILabel *orderDesc;
@property (strong, nonatomic) IBOutlet UILabel *orderRemark;
@property (strong, nonatomic) IBOutlet UILabel *orderPrice;
@property (strong, nonatomic) IBOutlet UILabel *orderSNLabel;
@property (strong, nonatomic) IBOutlet UILabel *orderUnickname;
@property (strong, nonatomic) IBOutlet UILabel *orderMobile;
@property (strong, nonatomic) IBOutlet UILabel *orderCarmodel;
@property (strong, nonatomic) IBOutlet UILabel *orderCarnum;
@property (strong, nonatomic) IBOutlet UILabel *orderWashtime;
@property (strong, nonatomic) IBOutlet UILabel *orderAddress;
@property (strong, nonatomic) IBOutlet UIImageView *image1;
@property (strong, nonatomic) IBOutlet UIImageView *image2;
@property (strong, nonatomic) IBOutlet UIImageView *image3;
@property (nonatomic, copy) NSString *currentCityName;
@property (nonatomic, assign) CGFloat startLatitude;
@property (nonatomic, assign) CGFloat startLongitude;
@property (nonatomic, assign) CGFloat endLatitude;
@property (nonatomic, assign) CGFloat endLongitude;

@end

@implementation NoFinishDetailController
{
    bool isGeoSearch;
    BMKGeoCodeSearch* _geocodesearch;
}

- (CLLocationManager *) locationManager {
    if (_locationManager == nil) {
        self.locationManager = [[CLLocationManager alloc]init];
    }
    return _locationManager;
}

- (CLGeocoder *)gecoder {
    if (_gecoder == nil) {
        self.gecoder = [[CLGeocoder alloc]init];
    }
    return _gecoder;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    __weak typeof(self)weakSelf = self;
    [self addLeftButtonWithImage:[UIImage imageNamed:@"返回箭头"] actionBlock:^{
        if ([weakSelf.fromWhereStr isEqualToString:@"抢单成功"]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LoadTableView" object:nil];
            [weakSelf.navigationController popToRootViewControllerAnimated:YES];
        } else {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }
    }];
    
    self.title = @"订单详情";
    if (ScreenWidth == 320) {
        self.line1.constant = self.line2.constant = 8.0f;
    } else if (ScreenHeight == 568) {
//        self.orderScrollView.scrollEnabled = NO;
        
    } else if (ScreenHeight == 480) {
//        [self.orderScrollView setContentSize:CGSizeMake(ScreenWidth, 425)];
        
    }
    if ([self.fromStr isEqualToString:@"待完成"]) {
        [self addBaiduMap];
        self.carBackgroundView.backgroundColor = [UIColor colorFromHexCode:@"f7f8f8"];
        
    } else if ([self.fromStr isEqualToString:@"已完成"]) {
        self.mapLabel.hidden = self.MapBackView.hidden = self.backgroundView.hidden = YES;
    }
    [self locationSetting];
}

#pragma mark -- 网络请求 --
-(void)webRequest_GetOrderDetailInfo
{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    hud.labelText = @"正在加载...";
    [self.view addSubview:hud];
    [hud show:YES];
    __weak typeof(self)weakself = self;
    NSDictionary *dict = @{@"sn":self.orderSN};
    [HttpRequestManager getMethod:KOrderDetalListInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (success) {
            NSMutableDictionary *dic = response[@"data"];
            weakself.orderName.text = dic[@"name"];
            weakself.orderDesc.text = dic[@"desc"];
            weakself.orderRemark.text = dic[@"remark"];
            weakself.orderPrice.text = [NSString stringWithFormat:@"¥%@",dic[@"price"]];
            weakself.orderUnickname.text = dic[@"unickname"];
            weakself.orderSNLabel.text = dic[@"sn"];
            weakself.orderWashtime.text = dic[@"washtime"];
            weakself.orderAddress.text = dic[@"carlocation"];
            weakself.orderCarmodel.text = dic[@"carmodel"];
            weakself.orderCarnum.text = dic[@"carnum"];
            weakself.orderMobile.text = dic[@"umobile"];
            weakself.endLatitude = [dic[@"lat"] floatValue];
            weakself.endLongitude = [dic[@"lon"] floatValue];
            [weakself.image1 sd_setImageWithURL:[NSURL URLWithString:dic[@"wash_pic1"]] placeholderImage:[UIImage imageNamed:@"洗车占位图"]];
            [weakself.image2 sd_setImageWithURL:[NSURL URLWithString:dic[@"wash_pic2"]] placeholderImage:[UIImage imageNamed:@"洗车占位图"]];
            [weakself.image3 sd_setImageWithURL:[NSURL URLWithString:dic[@"wash_pic3"]] placeholderImage:[UIImage imageNamed:@"洗车占位图"]];
        }else{
            
        }
    }];
}


- (IBAction)callUserMobileButtonAction:(UIButton *)sender {
    NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",self.orderMobile.text];
    UIWebView * callWebview = [[UIWebView alloc] init];
    [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
    [self.view addSubview:callWebview];
}

// 取消订单按钮
- (IBAction)cancelButtonAction:(UIButton *)sender {
    [[[UIAlertView alloc] initWithTitle:@"提示" message:@"真的要取消订单吗？" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消",nil]show];
    
}


// 确认订单按钮
- (IBAction)affirmButtonAction:(UIButton *)sender {
    AffirmOrderController *affirmVC = [[AffirmOrderController alloc]init];
    affirmVC.orderSN = self.orderSN;
    [self.navigationController pushViewController:affirmVC animated:YES];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        NSDictionary *dict = [[NSDictionary alloc]init];
        dict = @{@"sn":self.orderSN};
        __weak typeof(self)weakSelf = self;
        [HttpRequestManager postMethod:KCanaleOrderInterface parameters:dict completedMainBlock:^(BOOL success, id response, NSString *errMsg) {
            if (success) {
                [SVProgressHUD showSuccessWithStatus:@"订单取消成功"];
                if ([weakSelf.fromWhereStr isEqualToString:@"抢单成功"]) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"LoadTableView" object:nil];
                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                } else {
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }
            }else {
                [SVProgressHUD showErrorWithStatus:@"订单取消失败"];
            }
        }];
    }
}

#pragma mark ---添加地图---
- (void)addBaiduMap
{
    // 添加地图
    self.mapView = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 128)];
    [self.mapView setCenter:CGPointMake(ScreenWidth/2, 128/2)];
    [self.MapBackView addSubview:_mapView];
    _geocodesearch = [[BMKGeoCodeSearch alloc]init];
    [self configureCenterView];
    [self locationService];
}

#pragma mark ---地图中心点view的设置---
- (void)configureCenterView
{
    UIButton *myLocation = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth,128)];
    [myLocation setCenter:CGPointMake(ScreenWidth/2, 128/2)];
    [myLocation setBackgroundColor:[UIColor clearColor]];
    [myLocation addTarget:self action:@selector(locationBtn) forControlEvents:UIControlEventTouchUpInside];
    [myLocation setBackgroundImage:[UIImage imageNamed:@"定位"] forState:UIControlStateNormal];
    [self.MapBackView addSubview:myLocation];
    
}

- (void)locationBtn
{
    if (self.startLatitude != 0 && self.startLongitude != 0) {
        DetailViewController *detailVC = [[DetailViewController alloc]init];
        detailVC.cityStr = self.currentCityName;
        detailVC.startLatitudeFlo = self.startLatitude;
        detailVC.startLongitudeFlo = self.startLongitude;
        detailVC.endLatitudeFlo = self.endLatitude;
        detailVC.endLongitudeFlo = self.endLongitude;
        [self.navigationController pushViewController:detailVC animated:YES];
    }
}

#pragma mark  ---定位设置---
- (void)locationService
{
    // 定位
    //适配ios7
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0))
    {
        self.navigationController.navigationBar.translucent = NO;
    }
    _locService = [[BMKLocationService alloc]init];
    [_locService startUserLocationService];
    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    // 地图缩放比例
    [_mapView setZoomLevel:17];//级别，3-19
    _mapView.userTrackingMode = BMKUserTrackingModeFollow;
    _mapView.showsUserLocation = YES;//是否显示定位图层（即我的位置的小圆点）
    _mapView.userInteractionEnabled=YES;
    
    // 自定义精度圈
    BMKLocationViewDisplayParam *param = [[BMKLocationViewDisplayParam alloc] init];
    param.accuracyCircleStrokeColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    param.accuracyCircleFillColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    param.locationViewImgName = @"icon_center_point@2x";
    [_mapView updateLocationViewWithParam:param];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 反地理编码
        CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
        pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude,
            _locService.userLocation.location.coordinate.longitude};
        self.startLatitude = _locService.userLocation.location.coordinate.latitude;
        self.startLongitude = _locService.userLocation.location.coordinate.longitude;
        BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
        reverseGeocodeSearchOption.reverseGeoPoint = pt;
        BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
        if(flag)
        {
            //            NSLog(@"反地理编码检索发送成功");
        }
        else
        {
            NSLog(@"反地理编码检索发送失败");
        }
    });
}

/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)willStartLocatingUser
{
    NSLog(@"在地图View将要启动定位时");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    //    NSLog(@"最新用户方向：%@",userLocation.heading);
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    [_mapView updateLocationData:userLocation];
    //    NSLog(@"最新用户位置： 经度 %f,纬度 %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
}

/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser
{
    NSLog(@"地图View停止定位");
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error
{
    //    NSLog(@"定位失败");
}


- (void)dealloc {
    if (_mapView) {
        _mapView = nil;
    }
}

-(void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self; // 此处记得不用的时候需要置nil，否则影响内存的释放
    _locService.delegate = self;
    _geocodesearch.delegate = self;
    [self webRequest_GetOrderDetailInfo];
}

-(void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil; // 不用时，置nil
    _locService.delegate = nil;
    _geocodesearch.delegate = nil;
}

#pragma makr - poisearch
// 这个方法就是在Map移动 后执行，所以我们可以在这里获取移动后地图中心点的经纬度了。
- (void)mapView:(BMKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
    BMKCoordinateRegion region;
    CLLocationCoordinate2D centerCoordinate = mapView.region.center;
    region.center= centerCoordinate;
    
    // 反地理编码
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
    pt = (CLLocationCoordinate2D){centerCoordinate.latitude, centerCoordinate.longitude};
    
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag)
    {
        //        NSLog(@"反地理编码检索发送成功");
    }
    else
    {
        NSLog(@"反地理编码检索发送失败");
    }
}

-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == 0) {
        NSLog(@"我的位置：%@",result.address);
    }
}

#pragma mark -----定位到当前所在城市 ------
- (void)locationSetting {
    //检测定位服务是否打开
    if (![CLLocationManager locationServicesEnabled]) {
        NSLog(@"定位服务尚未打开");
        return;
    }
    //如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestWhenInUseAuthorization];
    }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse)
    {
        //必须写一下代码:requestWhenInUseAuthorization或者是 requestAlwaysAuthorization, 在使用之前需要先调用这个方法
        [self.locationManager requestWhenInUseAuthorization];
        //  设置代理
        _locationManager.delegate = self;
        // 设置定位精度
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 地位频率，每隔多少米定位一次
        CLLocationDistance  distance = 10.0;
        _locationManager.distanceFilter = distance;
        // 启动跟踪
        [_locationManager startUpdatingLocation];
    }
}

#pragma mark ---定位delegate---
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    // 数组里面存放的是CLLocation对象，一个CLLocation代表一个位置
    CLLocation *location = [locations lastObject];
    [self getCityByCoordinate:location];
    [manager stopUpdatingLocation];
}

//当定位失败的时候触发
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        // 访问拒绝
        [self alertViewShowWithMessage:@"访问地理位置被拒绝"];
    } if ([error code] == kCLErrorLocationUnknown) {
        
        [self alertViewShowWithMessage:@"无法获取地理位置"];
    }
}

#pragma mark --- 反地理编码 ---
- (void)getCityByCoordinate:(CLLocation *)location {
    [self.gecoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        CLPlacemark *placeMark = [placemarks firstObject];
        NSLog(@"%@--%@--%@",placeMark.administrativeArea,placeMark.locality,placeMark.subLocality);
        self.currentCityName = placeMark.locality;
    }];
}

#pragma mark - 警告视图
- (void)alertViewShowWithMessage:(NSString *)message {
    //    [[[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil]show];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
